package com.example.shirotest.study;

import java.util.ArrayList;
import java.util.Arrays;

public class GraphDemo {
    private ArrayList<String> vertextList;  //存储顶点集合
    private int[][] edges; //存储图对应的邻接矩阵
    private int numOfEdges; //表示边的数量
    private boolean[] isVisited;

    public static void main(String[] args) {
        int n = 5; // 节点个数
        String[] Vertexts = {"A","B","C","D","E"};
        //创建图对象
        GraphDemo graphDemo = new GraphDemo(n);
        //循环添加顶点
        for (String vertext : Vertexts) {
            graphDemo.insertVertext(vertext);
        }

        //添加边
        //A-B A-C B-C B-D B-E B-C
        graphDemo.insertEdge(0,1,1);
        graphDemo.insertEdge(0,2,1);
        graphDemo.insertEdge(1,2,1);
        graphDemo.insertEdge(1,3,1);
        graphDemo.insertEdge(1,4,1);

        graphDemo.showGraph();

        //对我们的dfs遍历
        System.out.println("Dfs foreach");
        graphDemo.dfs();
    }

    //构造器
    public GraphDemo(int n){
        edges = new int[n][n];
        vertextList = new ArrayList<>(n);
        numOfEdges = 0;
        isVisited = new boolean[n];
    }

    //得到第一个邻接节点的下标
    /**
     * @param index
     * @return 如果存在返回下标，否则返回-1
     */
    public int getFirstNeighbor(int index){
        for (int j = 0; j < vertextList.size(); j++) {
            if(edges[index][j] > 0){
                return j;
            }
        }
        return -1;
    }

    //根据前一个邻接节点的下标来取下一个邻接节点
    public int getNextNeighbor(int v1,int v2){
        for (int j = v2+1; j < vertextList.size(); j++) {
            if(edges[v1][j] > 0){
                return j;
            }
        }
        return -1;
    }

    //深度优先遍历算法
    public void dfs(boolean[] isVisited,int i){
        System.out.print( getValueByIndex(i) + "->");
        //将节点设置为已经访问
        isVisited[i] = true;
        //查找节点i的第一个邻接节点w
        int w = getFirstNeighbor(i);
        while (w != -1){
            if(!isVisited[w]){
                dfs(isVisited,w);
            }
            //如果w节点已经被访问过
            w = getNextNeighbor(i,w);
        }
    }
    //对dfs 进行一个重载，遍历我们所有的节点，并进行dfs
    public void dfs(){
        for (int i = 0; i < getNumOfVertex(); i++) {
            if(!isVisited[i]){
                dfs(isVisited,i);
            }
        }
    }

    //返回节点的个数
    public int getNumOfVertex(){
        return vertextList.size();
    }

    //返回边的数量
    public int getNumOfEdges(){
        return numOfEdges;
    }

    //返回节点i(下标)对应的数据
    public String getValueByIndex(int i){
        return vertextList.get(i);
    }

    //显示图对应的矩阵
    public void showGraph(){
        for (int[] edge : edges) {
            System.err.println(Arrays.toString(edge));
        }
    }


    //插入节点
    public void insertVertext(String vertex){
        vertextList.add(vertex);
    }

    //添加边
    public void insertEdge(int v1,int v2,int weight){
        edges[v1][v2] = weight;
        edges[v2][v1] = weight;
        numOfEdges++;
    }

}
